import os
import csv
import time
import struct
import usb.core
import usb.util
import pymysql

data_folder = 'D:/Data/'  # 保存CSV文件的文件夹
save_interval = 60  # 每300秒保存一个新的CSV文件
db_phy = {
    'host': '118.190.236.225',  # 主机
    'user': 'root',  # 用户名
    'password': '123456',  # 密码
    'port': 8306,  # 端口
    'database': 'cw'  # 数据库名
}

# 创建一个新的CSV文件，准备写入数据
def create_csv_file():
    current_time = time.strftime("%Y%m%d%H%M%S")
    filename = f"data_{current_time}.csv"
    filepath = os.path.join(data_folder, filename)
    csvfile = open(filepath, 'w', newline='')
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['Timestamp', 'Data'])  # 写入CSV文件的头部
    print(f"CSV file created at: {filepath}")  # 输出CSV文件的绝对路径

    return csvfile, csvwriter


current_dir = os.path.dirname(os.path.abspath(__file__))
print(current_dir)
os.add_dll_directory(current_dir)

dev = usb.core.find(idVendor=0x4321, idProduct=0x9876)
if dev is None:
    raise ValueError('Device not found')

dev.set_configuration()
cfg = dev.get_active_configuration()
intf = cfg[(0, 0)]

ep_out = usb.util.find_descriptor(
    intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)
assert ep_out is not None

ep_in = usb.util.find_descriptor(
    intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)
assert ep_in is not None


# 从usb读取数据
def read_from_usb():
    # 连接phy库
    connection_phy = pymysql.connect(**db_phy)
    # 创建游标对象
    cursor_phy = connection_phy.cursor()

    #start_time = time.time()
    #csvfile, csvwriter = create_csv_file()

    try:
        while True:
            ep_out.write('RequestData')
            size_array = ep_in.read(4)
            size = struct.unpack('<I', size_array)[0]
            data = ep_in.read(size)
            buffer = ''.join(chr(x) for x in data)
            # print(''.join(chr(x) for x in data))
            # 获取当前时间戳
            timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
            # 插入数据库
            insert_query = "INSERT INTO base (startdate, content_data) VALUES (%s, %s)"
            rows = (timestamp, buffer)
            cursor_phy.execute(insert_query, rows)
            # 提交事务
            connection_phy.commit()

            # 写入CSV文件
            #csvwriter.writerow([timestamp, buffer])
            #print(f"Data saved: {buffer}")
            # 检查是否需要创建新的CSV文件
            #if time.time() - start_time >= save_interval:
                #csvfile.close()
                #csvfile, csvwriter = create_csv_file()
                #start_time = time.time()
            time.sleep(1)

    except KeyboardInterrupt:
        print("Interrupted by user")
    except pymysql.Error as error:
        print(error)
    finally:
        #csvfile.close()
        usb.util.dispose_resources(dev)
        cursor_phy.close()
        connection_phy.close()

if __name__ == "__main__":
    read_from_usb()